// 原生广告
import {
  initNativeSdk,
  initBqtSdk,
  getManuAdv,
} from './native_sdk.js'
// banner广告
import {
  initBannerSdk,
  hideBannerAdv,
  destroyBannerAdv,
  getSingleBanner
} from './banner_sdk.js'
// video广告
import {
  initVideoAdvSdk,
  playVideoReward,
  getVedioAdv,
} from './video_adv_sdk.js'
import { eventEmitter } from './emitter.js'
var ad_sdk_global = {
  // 当前设备信息，必传
  deviceInfo: null,
  // 渠道号
  qudao: 'NULL',
  // 链接id
  link_id: 'NULL',
  // 是否支持厂商广告
  serviceAd: true,
  // sdk初始化状态，0未初始化，1初始化中，2初始化完成
  initStatus: 0,
  // 是否创建过视频广告对象
  isCreate: false,
  // 初始化时页面的名称
  pageUrl: '',
  vivoAdCount: 1, //vivo请求广告个数
  ad_group_id: 'NULL', //广告组id
  ad_plan_id: 'NULL', // 广告计划id
  source_pkg: 'NULL', //来源包名
  unionid: 'NULL', // 媒体位id
  utm_content: 'NULL', // 创意id
  vivoChannelFilter: null,
  vivoChannel: '', // vivo上报的渠道的值
  materialType: 1, //素材和icon优先级 1素材 2icon
  defaultAdImg: 'https://img.sysenbo.top/image/2022-06-29/adDefaultImg1.png', // 广告默认图片
  adNewPostionConfig: null,
  nativeAdData: [], // 原生ecpm广告数据
  isBqtCanShowDialog: 0,
  adErrorReportFlag: true, // 无广告是否诸云上报
  requestTimeLimit: 100, // 广告请求频率限制
  requestNumLimit: 10, // 广告请求失败次数限制（广告请求失败次数达到该值，按请求频率限制时间请求广告）
  videoPlaying: false,
  rewardTimer: null,
  preloadVideo: false,
  preVideoAd: null,
  rewardFlag: false, // 激励视频节流
  popShowNum: 0, // 上报用户当前弹窗展示、点击次数（递增）
  showTimers: {}, // 曝光频控定时器
  showControlList: [],// 曝光频控平台列表
  responseList: [], // 存储曝光频控广告
}
/**
 * 广告SDK初始化
 * @param obj.deviceInfo 设备信息
 * @param obj.qudao 渠道号
 * @param obj.link_id 链接id
 * @param obj.preloadingNum 预加载的广告个数
 * @param obj.materialType 素材和icon优先级
 * @param obj.success 初始化成功回调
 * @param obj.fail 初始化失败回调
 */
function initSdk(obj) {
  return new Promise((resolve, reject) => {
    if (ad_sdk_global.initStatus == 2 && !obj.isCheckStatus) {
      obj && obj.success && obj.success()
      return resolve()
    }
    // 参数初始化
    assignParame(obj)
    // 判断手机是否支持厂商
    try {
      require('@service.ad')
    } catch (err) {
      ad_sdk_global.serviceAd = false
    }
    initBannerSdk()
    initNativeSdk()
    initVideoAdvSdk()
    initBqtSdk()
    // 初始化成功
    ad_sdk_global.initStatus = 2
    obj && obj.success && obj.success()
    resolve()
  })
}
// 初始化参数赋值
function assignParame(obj) {
  LOG('AD', 'assignParame==>arguments', obj)
  ad_sdk_global.initStatus = 1
  ad_sdk_global.nativeAdData = []
  let deviceObj = obj.deviceInfo
  let tembrand = deviceObj.brand && deviceObj.brand.toLowerCase()
  if (tembrand == 'vivo') {
    tembrand = 'vivo'
  } else {
    tembrand = 'other'
  }
  deviceObj.brand = tembrand
  ad_sdk_global.deviceInfo = deviceObj
  ad_sdk_global.qudao = obj.qudao ? obj.qudao : 'NULL'
  ad_sdk_global.link_id = obj.link_id ? obj.link_id : 'NULL'
  ad_sdk_global.ad_plan_id = obj.adPlanId ? obj.adPlanId : 'NULL'
  ad_sdk_global.ad_group_id = obj.adGroupId ? obj.adGroupId : 'NULL'
  ad_sdk_global.source_pkg = obj.sourcePkg ? obj.sourcePkg : 'NULL'
  ad_sdk_global.utm_content = obj.utm_content ? obj.utm_content : 'NULL'
  ad_sdk_global.unionid = obj.unionid ? obj.unionid : 'NULL'
  ad_sdk_global.vivoChannelFilter = obj.vivoChannelFilter
  ad_sdk_global.materialType = obj.materialType ?? 2
  ad_sdk_global.vivoChannel = joinVivoChannelParams()
  ad_sdk_global.adNewPostionConfig = obj.adNewPostionConfig
  ad_sdk_global.isBqtCanShowDialog = obj.isBqtCanShowDialog || 0
  ad_sdk_global.adErrorReportFlag =
    TACTICS_SDK.getGlobalData('ad_pool').is_none_ad_report || 0
  ad_sdk_global.adNewPostionConfig.ad_protogenesis.forEach(item => {
    ad_sdk_global.nativeAdData.push(item)
  });
  // 是否存在曝光频控
  const frequencyControl = ad_sdk_global.adNewPostionConfig.frequency_control_config
  if (frequencyControl) {
    ad_sdk_global.showControlList = frequencyControl.frequency_control.filter(v => v.flag)
  }
}
/**
 *
 * @param {String} channelId 渠道
 * @param {String} linkId 链接id
 * @param {String} ad_plan_id 广告计划id
 * @param {String} source_pkg 来源包名
 * @param {String} unionid 媒体位id
 * @param {String} brand 厂商
 */
function joinVivoChannelParams() {
  LOG('AD', 'joinVivoChannelParams', ad_sdk_global.vivoChannelFilter)
  if (ad_sdk_global.deviceInfo.brand !== 'vivo') return ''
  if (
    ad_sdk_global.vivoChannelFilter &&
    typeof ad_sdk_global.vivoChannelFilter == 'object'
  ) {
    let result = ''
    for (let [key, value] of Object.entries(ad_sdk_global.vivoChannelFilter)) {
      LOG('AD', [key, value]) // [['name','liming'],['age','29']]
      if (value) {
        switch (key) {
          case 'campaign_id_status':
            result = result + '|' + ad_sdk_global.ad_plan_id
            break
          case 'channel_status':
            result = result + '|' + ad_sdk_global.qudao
            break
          case 'link_status':
            result = result + '|' + ad_sdk_global.link_id
            break
          case 'site_status':
            result = result + '|' + ad_sdk_global.unionid
            break
          case 'source_pkg_status':
            result = result + '|' + ad_sdk_global.source_pkg
            break
          case 'utm_content_status':
            result = result + '|' + ad_sdk_global.utm_content
            break
          case 'ad_scene_status':
            result = result + '|' + '@@'
            break
          case 'ad_group_id':
            result = result + '|' + ad_sdk_global.ad_group_id
            break
        }
      } else {
        result = result + '|' + 'NA'
      }
    }
    return result == '' ? '|||||||' : result.substring(1)
  } else {
    return '|||||||'
  }
}
/**
 * 数组重排
 * @param advIdArr 广告位数组
 * @param isHz 请求频率开关
 * @param time 连续请求失败停止时间
 */
function computeAdvIdArr(advIdArr = [], isHz = false, time = 5000) {
  // 去空
  let curArr = [].concat(advIdArr.filter((item) => item))
  let maxLayer = curArr.length
  let curLayer = 0

  curArr = curArr.map((item) => {
    let sortItem = sortArray(item.adId.split(','), isHz, time, item.current_ctr_status)
    return {
      curIndex: 0,
      maxIndex: sortItem.length,
      adsArr: sortItem,
      ecpm: Number(item.ecpm) || 0,
      type: item.ad_type ? item.ad_type.toLowerCase() : '',
      time: Number(item.time) || 0,
      target_price: Number(item.target_price) || 0,
    }
  })
  return {
    maxLayer, //最大层级
    curLayer, //当前层级
    layers: curArr,
    yetLayer: 0, // 有广告层级
  }
}
/**
 * 数组重排
 * @param failNum 请求失败次数
 * @param isHz 请求频率开关
 * @param current_status 广告位点击率状态
 */
function sortArray(arr, isHz = false, time = 5000, current_status) {
  var temp_array = new Array()
  for (var index in arr) {
    if (isHz) {
      temp_array.push({
        id: arr[index],
        _failNum: 0,
        current_status: current_status ? current_status[arr[index]] : 1,
        get failNum() {
          return this._failNum;
        },
        set failNum(flag) {
          this._failNum++
          if (flag) {
            setTimeout(() => {
              this._failNum = 0
            }, time);
          }
        }
      })
    } else {
      temp_array.push(arr[index])
    }
  }
  return shuffle(temp_array)
}
function shuffle(arr) {
  var l = arr.length
  var index, temp
  while (l > 0) {
    index = Math.floor(Math.random() * l)
    temp = arr[l - 1]
    arr[l - 1] = arr[index]
    arr[index] = temp
    l--
  }
  LOG('AD', arr)
  return arr
}
function getMaterialUrlByAdData(adObj) {
  let materialUrl = ''
  let icon = adObj.icon && typeof adObj.icon != 'object' ? adObj.icon : ''
  let img = ''
  img = adObj.imgUrlList && adObj.imgUrlList[0] ? adObj.imgUrlList[0] : ''
  if (ad_sdk_global.materialType == 2) {
    materialUrl = icon ? icon : img
  } else {
    materialUrl = img ? img : icon
  }
  if (
    (materialUrl && materialUrl.indexOf('.mp4') != -1) ||
    !materialUrl ||
    typeof materialUrl != 'string'
  ) {
    materialUrl = ad_sdk_global.defaultAdImg
  }
  return materialUrl
}
/**
 * 重置广告失败code、msg
 * @param type 失败类型（无广告）
 * @param data fail、adError回调值
 */
const errMsgFormat = (type = '', data = '') => {
  let err = ''
  if (data && typeof data === 'object') {
    err = data.errCode ? data.errCode : '无errCode';
    err = `${err}-${data.errMsg ? data.errMsg : '无errMsg'}`;
  } else {
    err = JSON.stringify(data)
  }
  return type + err
}
/**
 * 广告按钮点击
 * @param {*} obj 广告对象
 */
function clickManuAdvForBtn(obj, clickType) {
  if (obj && obj.advDetail && obj.advDetail.adId) {
    uploadAdInfo('click', obj, clickType)
  }
}
/**
 * 广告图片点击
 * @param {*} obj 广告对象
 */
function clickManuAdvForImg(obj, clickType) {
  LOG('AD', `广告ADSDK========>广告图片点击`, obj)
  if (obj && obj.advDetail && obj.advDetail.adId) {
    uploadAdInfo('click', obj, clickType)
  }
}

function uploadAdInfo(eventId, obj, clickType = 'btn') {
  if (!obj || !obj.id) return
  let postParam = new Object()
  postParam.ad_id = obj.id
  postParam.ad_network = obj.ad_network || 1
  postParam.ad_type = obj.ad_type || '原生'
  postParam.result = obj.result || ''
  postParam.page_name = obj.scenario || '厂商广告联盟'
  postParam.ad_position = obj.popName || '广告池'
  postParam.page_type = obj.popGroupName || '广告池'
  postParam.ad_style = obj.ad_style || '无'
  postParam.requestNum = `${obj.requestNum || '1'}`
  postParam.ext_field_8 = obj.advDetail
    ? obj.advDetail.appInfo
      ? obj.advDetail.appInfo.appName
      : obj.advDetail.appName || obj.title || obj.advDetail.title
    : '无'
  postParam.ext_field_2 = obj.layer >= 0 ? obj.layer + 1 + '' : '1'
  postParam.referer = obj.adTurn + '' || '1'
  postParam.scene = obj.scene || '自动请求'
  postParam.ext_field_3 = obj.adRegion || ''
  postParam.ext_field_6 = obj.client || ''
  postParam.ext_field_1 = obj.isBidding && obj.advDetail ? obj.advDetail.ecpm + '' : ''
  let element = clickType == 'btn' ? '按钮' : '素材'
  let {
    ad_id,
    ad_network,
    ad_type,
    page_name,
    page_type,
    ad_position,
    result,
    ad_style,
    requestNum,
    ext_field_8,
    ext_field_2,
    referer,
    scene,
    ext_field_3,
    ext_field_6,
    ext_field_1
  } = postParam
  const ext_field_9 = requestNum
  LOG('AD', 'uploadAdInfo==============>', eventId, postParam, clickType)
  switch (eventId) {
    case 'request':
      if (!ad_sdk_global.adErrorReportFlag && obj.result.includes('无广告'))
        return
      COMMON_REPORT_UTILS.ad_sdk_request_report(
        ad_id,
        ad_network,
        ad_type,
        page_name,
        page_type,
        ad_position,
        result,
        ext_field_9,
        ad_style,
        ext_field_8,
        ext_field_2,
        referer,
        scene,
        ext_field_1
      )
      break
    case 'show':
      COMMON_REPORT_UTILS.ad_sdk_show_report(
        ad_id,
        ad_network,
        ad_type,
        page_name,
        page_type,
        ad_position,
        ext_field_9,
        ad_style,
        result,
        ext_field_8,
        ext_field_2,
        referer,
        scene,
        ext_field_1
      )
      break
    case 'click':
      COMMON_REPORT_UTILS.ad_sdk_click_report(
        ad_id,
        ad_network,
        ad_type,
        page_name,
        page_type,
        ad_position,
        element,
        ext_field_9,
        ad_style,
        ext_field_8,
        ext_field_2,
        referer,
        scene,
        ext_field_1,
        ext_field_3,
        ext_field_6,
      )
      break
    case 'render':
      COMMON_REPORT_UTILS.ad_sdk_render_report(
        ad_id,
        ad_network,
        ad_type,
        page_name,
        page_type,
        ad_position,
        ext_field_9,
        ad_style,
        referer,
        ext_field_8,
        ext_field_2,
        result,
        scene,
        ext_field_1
      )
      break
    case 'abandon':
      COMMON_REPORT_UTILS.ad_sdk_abandon_report(
        ad_id,
        ad_network,
        ad_type,
        page_name,
        page_type,
        ad_position,
        ext_field_9,
        ad_style,
        referer,
        ext_field_8,
        ext_field_2,
        result,
        '是',
        scene,
        ext_field_1
      )
      break
    case 'success':
      postParam.event_name = '视频广告播放完成SDK'
      postParam.event_id = 'ad_sdk_success'
      break
    case 'incomplete':
      postParam.event_name = '视频广告播放未完成SDK'
      postParam.event_id = 'ad_sdk_incomplete'
      break
    case 'install':
      COMMON_REPORT_UTILS.ad_sdk_install_report(
        ad_id,
        ad_network,
        ad_type,
        page_name,
        page_type,
        ad_position,
        ext_field_9,
        ad_style,
        ext_field_8,
        referer,
        ext_field_2,
        scene,
        ext_field_3,
      )
      break
    case 'take':
      COMMON_REPORT_UTILS.ad_sdk_take(
        ad_id,
        ad_network,
        ad_type,
        page_name,
        page_type,
        ad_position,
        ad_style,
        ext_field_9,
        referer,
        scene,
        ext_field_8,
        ext_field_2,
        result,
        scene,
        ext_field_1
      )
      break
    case 'control':
      COMMON_REPORT_UTILS.ad_frequency_control(postParam)
      break
  }
}
export default {
  ad_sdk_global,
  eventEmitter,
  initSdk,
  sortArray,
  computeAdvIdArr,
  getManuAdv,
  clickManuAdvForBtn,
  clickManuAdvForImg,
  getVedioAdv,
  playVideoReward,
  hideBannerAdv,
  destroyBannerAdv,
  uploadAdInfo,
  getMaterialUrlByAdData,
  errMsgFormat,
  getSingleBanner,
}
